<script setup lang="ts">
import { ref, h, reactive, onMounted, watch, onBeforeMount } from "vue";
import { ReVxeGrid } from "@/components/ReVxeTable";
import { VxeGridPropTypes, VxeUI } from "vxe-table";
import { VxeFormProps, VxeButton, VxeSwitch, VxeTag } from "vxe-pc-ui";
import useTaxSourcesIdStore from '@/store/modules/taxSourcesId'
import {
  InvoiceOfNumber,
  InfoTax,
  MerchantsInfoByTaxSourcesId,
  listmerchantsInfo
} from "@/api/welcome";
import { useRouter } from "vue-router";

const router = useRouter();
const reVxeGridRef = ref();
const taxSourcesId =  ref<any>(0);
let taxSourcesIdStates = null
taxSourcesIdStates = useTaxSourcesIdStore()
onMounted(() => { 
  
  
});
onBeforeMount(() =>{
  taxSourcesId.value = taxSourcesIdStates.taxSourcesId
  formOptions.data.taxSourcesId = taxSourcesIdStates.taxSourcesId  
  // console.log( formOptions.data,' formOptions.data')
  getInvoiceOfNumber();
      getInfoTax();
      taxSourcesId && getMerchantsInfoByTaxSourcesId( taxSourcesId.value )
})
watch(()=>{
      return taxSourcesIdStates.taxSourcesId
    },(newVal, oldVal)=>{
      taxSourcesId.value = taxSourcesIdStates.taxSourcesId
      getInvoiceOfNumber();
      getInfoTax();
      taxSourcesId && getMerchantsInfoByTaxSourcesId( taxSourcesId.value )
      formOptions.data.taxSourcesId = taxSourcesIdStates.taxSourcesId
      reVxeGridRef.value.loadData();
     
    }, {
      // immediate: true
    })

const columns: VxeGridPropTypes.Columns<any> = [
  // { type: "checkbox", title: "", width: 60, align: "center" },
  {
    title: "合作公司名称",
    field: "merchantsName",
    showOverflow: true,
    align: "center",
    minWidth: 140
  },
  {
    title: "统一信用代码",
    field: "enterpriseIdNumber",
    showOverflow: true,
    align: "center",
    minWidth: 140
  },
  {
    title: "合同",
    field: "contract",
    showOverflow: true,
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "公司合同",
          onClick() {
            console.log(row);
            router.push({
              path: "/contract/merchantsContract",
              query: { merchantsName: row.merchantsName }
            });
          }
        }),
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "个人合同",
          onClick() {
            router.push({
              path: "/contract/averageUserContract",
              query: { merchantsName: row.merchantsName}
            });
          }
        })       
      ]
    }
  },
  {
    title: "项目",
    field: "projectManage",
    showOverflow: true,
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "项目记录",
          onClick() {
            console.log(row);
            router.push({
              path: "/projectManage/project",
              query: { merchantsName: row.merchantsName }
            });
          }
        }),
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "任务列表",
          onClick() {
            router.push({
              path: "/projectManage/task",
               query: { merchantsName: row.merchantsName }
            });
          }
        })       
      ]
    }
  },
  {
    title: "资金",
    field: "capitalManage",
    showOverflow: true,
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "充值记录",
          onClick() {
            console.log(row);
            router.push({
              path: "/capitalManage/recharge",
              query: { merchantsName: row.merchantsName }
            });
          }
        }),
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "发放记录",
          onClick() {
            router.push({
              path: "/capitalManage/grant",
              query: { merchantsName: row.merchantsName }
            });
          }
        })       
      ]
    }
  },
  {
    title: "发票",
    field: "invoiceManage",
    showOverflow: true,
    align: "center",
    minWidth: 120,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "发票记录",
          onClick() {
            console.log(row);
            router.push({
              path: "/invoiceManage/record",
             query: { merchantsName: row.merchantsName }
            });
          }
        })           
      ]
    }
  },
  {
    title: "业务",
    field: "business",
    showOverflow: true,
    align: "center",
    minWidth: 140,
    slots: {
      default: ({ row }) => [
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "完税凭证",
          onClick() {
            console.log(row);
            router.push({
              path: "/business/settle",
              query: { merchantsName: row.merchantsName }
            });
          }
        }),
        h(VxeButton, {
          status: "primary",
          mode: "text",
          size: "mini",
          content: "验收单",
          onClick() {
            console.log(row);
            router.push({
              path: "/business/voucher",
             query: { merchantsName: row.merchantsName }
            });
          }
        })           
      ]
    }
  },
  {
    title: "创建时间",
    field: "createTime",
    showOverflow: true,
    align: "center",
    minWidth: 140
  }
];
// 筛选相关
const formRef = ref();
interface FormDataVO {
  merchantsName: string; //输入的商户名称
  taxSourcesId: number | string; //税源地
  createTimeStart: number | string; //开始日期
  createTimeEnd: number | string; //结束日期  
  businessTimeStart: number | string; //业务开始日期
  businessTimeEnd: number | string; //业务结束日期  
}
const formOptions = reactive<VxeFormProps<FormDataVO>>({
  data: {
    merchantsName: "",
    taxSourcesId: taxSourcesId.value,
    createTimeStart: "",
    createTimeEnd: "",
    businessTimeStart: "", //业务开始日期
    businessTimeEnd:"", //业务结束日期   
  },
  items: [
    {
      field: "merchantsName",
      title: "",
      span: 6,
      itemRender: {},
      slots: { default: "merchantsName" }
    },
    {
      field: "timeRang",
      title: "",
      span: 6,
      itemRender: {},
      slots: { default: "timeRang" }
    },
    {
      field: "businesstimeRang",
      title: "",
      span: 6,
      itemRender: {},
      slots: { default: "businesstimeRang" }
    },
    { align: "left", span: 4, slots: { default: "active" } }
  ]
});
const functions: Record<string, string> = {
  add: "platform.client.index.add",
  edit: "platform.client.index.edit",
  view: "platform.client.index.view",
  delete: "platform.client.index.delete"
};

interface RestaurantItem {
  id: number
  value: string
}
const listMerchantsInfoByTaxSourcesId = ref<RestaurantItem[]>([]);
const getMerchantsInfoByTaxSourcesId = (taxSourcesId?:
  number): void => {
  MerchantsInfoByTaxSourcesId(taxSourcesId).then((res: any) => {
    listMerchantsInfoByTaxSourcesId.value = res.data;
  });
};
// 根据税源地ID查询合作公司列表搜索
const fetchSuggestions = (queryString: any, cb: (params: any) => void) => { 
  const results = queryString
    ? listMerchantsInfoByTaxSourcesId.value.filter(createFilter(queryString))
    : listMerchantsInfoByTaxSourcesId.value  
    cb(results)
  
};
const createFilter = (queryString: string) => {
  return (listMerchantsInfoByTaxSourcesId: RestaurantItem) => {
    return (
      listMerchantsInfoByTaxSourcesId.value.indexOf(queryString) === 0
    )
  }
}
const autoselect = (res: any) => {
  console.log(res);
  formOptions.data.merchantsName = res.value;
};
// 重置内容
const handleInitialFormParams = () => {
  formOptions.data = <FormDataVO>{
    merchantsName: "",
    taxSourcesId: "",
    createTimeStart: "",
    createTimeEnd: "",
    businesstimeRang:[],
    businessTimeStart: "", //业务开始日期
    businessTimeEnd:"", //业务结束日期    
  };
};
const handleSearch = () => {
  console.log(formOptions.data,'formOptions.data')
  if (formOptions.data?.timeRang?.length) {
    formOptions.data.createTimeStart = formOptions.data.timeRang[0];
    formOptions.data.createTimeEnd = formOptions.data.timeRang[1];
    delete formOptions.data.timeRang;
  }
  if (formOptions.data?.businesstimeRang?.length) {
    formOptions.data.businessTimeStart = formOptions.data.businesstimeRang[0];
    formOptions.data.businessTimeEnd = formOptions.data.businesstimeRang[1];
   delete formOptions.data.businesstimeRang;
  }
  reVxeGridRef.value.loadData();
};
const handleReset = async () => {
  await handleInitialFormParams();
  reVxeGridRef.value.loadData("reset");
};

// 获取首页开票数量
const invoiceOfNumberDetail = ref<any>({});
const getInvoiceOfNumber = (): void => {
  InvoiceOfNumber({
    pageNum: 1,
    pageSize: 10,
    taxSourcesId: taxSourcesId.value
  }).then((res: any) => {
    invoiceOfNumberDetail.value = res.data;
  });
};
// 获取税务端开票数量资金金额
const InfoTaxDetail = ref<any>({});
const getInfoTax = (): void => {
  InfoTax(
    {
    pageNum: 1,
    pageSize: 10,
    taxSourcesId: taxSourcesId.value
  }
  ).then((res: any) => {
    InfoTaxDetail.value = res.data;
  });
};


</script>
<template>
  <div>
    <el-card :shadow="`never`">
      <vxe-form ref="formRef" v-bind="formOptions">
        <template #merchantsName="{ data }">
          <el-autocomplete
            clearable
            v-model="data.merchantsName"
            :fetch-suggestions="fetchSuggestions"
            placeholder="请输入公司名称全称"
            value-key="value"
            @select="autoselect"
          >
          </el-autocomplete>
        </template>
        
        <template #timeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.timeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
        <template #businesstimeRang="{ data }">
          <el-date-picker
            clearable
            style="width: 100%"
            v-model="data.businesstimeRang"
            type="daterange"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="业务数据开始"
            end-placeholder="业务数据结束"
          />
        </template>
        <template #active>
          <el-button @click="handleSearch" native-type="submit" type="primary"
            >搜索</el-button
          >
          <el-button @click="handleReset" native-type="reset">重置</el-button>
         
        </template>
      </vxe-form>
    </el-card>

    <el-row :gutter="16" style="margin:10px 0px">       
        <el-col :span="5">
          <el-card :shadow="`never`"> 
            <div class="mx-item">
              <view class="mx-label" type="info">资金金额（元）</view>
              <view class="mx-text" type="info">{{ InfoTaxDetail.amountOfTheRecharge }}</view>
            </div>
            <div class="mx-item">
              <el-text class="mx-label" type="info">资金金额（元）</el-text>
              <el-text class="mx-text" type="info">{{ InfoTaxDetail.amountOfBusiness }}</el-text>
            </div>
          </el-card>
    </el-col>
    <el-col :span="11">
      <el-card :shadow="`never`"> 
        <el-descriptions  direction="vertical" style="margin-top:12px">
          <el-descriptions-item label="开票数量（张）"> <el-text class="mx-text" type="info">{{ invoiceOfNumberDetail.invoiceOfNumber }}</el-text></el-descriptions-item>
          <el-descriptions-item label="开票总额（元）"> <el-text class="mx-text" type="info">{{ invoiceOfNumberDetail.totalInvoiceAmount }}</el-text></el-descriptions-item> 
          <el-descriptions-item label="增值税纳税总额（元）"> <el-text class="mx-text" type="info">{{ invoiceOfNumberDetail.totalTaxAmount }}</el-text></el-descriptions-item>        
        </el-descriptions>
        
         </el-card>
    </el-col>
  </el-row>
  

    <el-card :shadow="`never`" class="table-card">
      <ReVxeGrid
        ref="reVxeGridRef"
        :request="listmerchantsInfo"
        :functions="functions"
        :searchParams="formOptions.data"
        :columns="columns"
        :action="false"    
      />
    </el-card>    
  </div>
</template>
<style scoped>
.el-card__body{
  padding:0px!important;
}
.mx-item{
  margin-bottom:6px;
  text-align: center;
  display: flex;
  flex-direction: column;
}
.mx-label{
  font-size: 14px;
  color:#27344B;
  line-height:23px;
}
.mx-text{
  font-weight: 600;
font-size: 18px;
color: #FF6A00;
line-height: 25px;
  
}
</style>